#include "libc/stdint.h"

void memset(char* str, int num, uint32_t size){
    for(uint32_t i = 0; i < size; ++i){
        str[i] = num;
    }
}


uint32_t strlen(char* str){
    uint32_t i = 0;

    while(str[i] != '\0'){
        i++;
    }

    return i;
}


bool strcmp(char* str1, char* str2){
    uint32_t len1 = strlen(str1);
    uint32_t len2 = strlen(str2);
    if(len1 != len2) return false;
    for(uint32_t i = 0; i < len1; ++i){
        if(str1[i] != str2[i]){
            return false;
        }
    }
    return true;
}

void get_next(char* p, int *next){
    uint32_t len = strlen(p);
    next[0] = -1;

    int k = -1;
    int j = 0;
    while(j < len - 1)
    { 
        if(k == -1 || p[j] == p[k]) 
        { 
            ++j; 
            ++k; 
            next[j] = k; 
        } 
        else 
        { 
            k = next[k];  
        } 
    } 

    // printk("\r\n");
    // for(int i= 0; i < len; ++i){
    //     printk("\ni = %d : %d ",i, next[i]);
    // }
    // printk("\r\n");
} 
 
int strKmp(char* s, char* p) {
    int next[256] = {0};
    get_next(p, next);

    int len1 = strlen(s); 
    int len2 = strlen(p);
    if(len2==0) return 0; 
    int i=0,j=0; 
    while (i < len1 && j < len2){
        if(j==-1||s[i]==p[j]){ 
            i++;j++; 
            if(j==len2){ 
                return i - j; 
            } 
        } 
        else{
            j = next[j]; 
             
        } 
    } 
    return -1; 
} 

// char* strtok(char* str1, char* str2){
//     // todo
//     int k = strKmp(str1,str2);
    
//     return true;
// }

void strcat(char* result, char* str1, char* str2){
    uint32_t i = 0;
    while(str1[i] != '\0'){
        result[i] = str1[i];
        ++i;
    }

        printk(result);

    uint32_t j = 0;
    while(str2[j] != '\0'){
        result[i] = str2[j];
        ++i;
        ++j;
    }
    result[i] = '\0';
}


void reverse(char str[], int num){
    int i = 0;
    int j = num;
    while(i<j){
        char tmp = str[i];
        str[i] = str[j];
        str[j] = tmp;
        ++i;
        --j;
    } 
}


int atoi(char* buf, unsigned long long int num, int radix){ // radix 代表进制
    int i = 0;

    do{
        unsigned long long int a = num % radix;

        buf[i] = (a < 10) ? ('0' + a) : ('A' + a - 10);
        i++;
        num /= radix;
    }while(num != 0);

    buf[i] = '\0';
    reverse(buf, i-1);
    return i;
}
